import React, {PureComponent} from 'react';
import {Upload, Icon, message, Modal} from 'antd';
import {UPLOAD_URL} from 'constant/url';
import style from './avatar.less';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  //Modal.confirm({
  //title: '更新图片',
  //content: '是否更新车辆图片',
  //okText: '是',
  //cancelText: '否',
  //onOk: function() {
  //me.deleteCommonWordGroup({...deleteGroup});
  //},
  //});

  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小应小于2MB!');
  }
  return isLt2M;
}

class AvatarUpload extends PureComponent {
  state = {
    loading: false,
    imageUrl: this.props.defaultImg,
  };
  handleChange = info => {
    let {onEdit} = this.props;
    if (info.file.status === 'uploading') {
      this.setState({loading: true});
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, imageUrl => {
        
        Modal.confirm({
          title: '更新图片',
          content: '是否更新车辆图片',
          okText: '是',
          cancelText: '否',
          onOk: () => {
            onEdit(info.file.response.data.url).then(() => {
              this.setState({
                imageUrl,
                loading: false,
              });
            });
          },
        });
      });
    }
  };
  componentDidMount() {
    this.setState({
      imageUrl: this.props.defaultImg,
    });
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.defaultImg != this.props.defaultImg) {
      this.setState({
        imageUrl: nextProps.defaultImg,
      });
    }
  }
  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const imageUrl = this.state.imageUrl;
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className={style['avatar-uploader']}
        showUploadList={false}
        action={UPLOAD_URL}
        beforeUpload={beforeUpload}
        onChange={this.handleChange}>
        {imageUrl ? (
          <img src={imageUrl} alt="" width={640} height={360} />
        ) : (
          uploadButton
        )}
      </Upload>
    );
  }
}
export default AvatarUpload;
